package com.example.demo.config;

import com.example.common.tools.AppVariable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截校验
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 检验用户是否登录，没登陆则跳转到 login.html 页面
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //检验 session 是否为空
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(AppVariable.USER_SESSION_KEY) == null) {
            response.sendRedirect("/login.html");
            return false;
        }
        return true;
    }
}
